﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using smartcrm.Models;
using smartcrm.Utilities;

namespace smartcrm.Controllers
{
    [Authorization]
    public class ContactController : BaseController
    {
        public ActionResult Index(string Keywords, string sCustomerNo, string cgb, string page)
        {
            ContactList contacts = new ContactList();
            List<Customer> allCustomers = Context.Customer.ToList();

            PagerConfig pconfig = GetPagerConfig(page);
            contacts.RouterDirectory.Add("Keywords", Keywords);
            contacts.RouterDirectory.Add("sCustomerNo", sCustomerNo);

            IQueryable<Contact> query = Context.Contact.Where(m => m.IsActive == true && m.CompanyNo == CompanyNo);

            if (!string.IsNullOrEmpty(Keywords))
            {
                Keywords = Keywords.Trim();
                query = query.Where(m => m.ContactName.Contains(Keywords) || m.SearchKey.Contains(Keywords));
            }

            if (!string.IsNullOrEmpty(sCustomerNo))
            {
                sCustomerNo = sCustomerNo.Trim();
                query = query.Where(m => m.CustomerNo == sCustomerNo);
            }

            if (!string.IsNullOrEmpty(cgb) && cgb == "1")
            {
                contacts.backButtonVisibility = "inline";
            }
            else
            {
                contacts.backButtonVisibility = "none";
            }
            contacts.Contacts = query.ToList();

            contacts.sCustomerNo = sCustomerNo;
            contacts.Keywords = Keywords;

            contacts.Keywords = Keywords;

            contacts.DdlCustomer = BindCustomerDdl();
            BindCustomerName(contacts, allCustomers);

            pconfig.TotalRecord = contacts.Contacts.Count;
            contacts.Contacts = contacts.Contacts.ToPagedList(pconfig.CurrentPage, pconfig.PageSize);

            contacts.PagerConfig = pconfig;

            return View(contacts);
        }

        private void BindCustomerName(ContactList model, List<Customer> allCustomers)
        {
            Customer customer;
            foreach (Contact c in model.Contacts)
            {
                customer = allCustomers.FirstOrDefault(m => m.CustomerNo == c.CustomerNo);
                if (customer != null)
                {
                    c.CustomerNo = customer.CustomerShortName;
                }
                else
                {
                    c.CustomerNo = string.Empty;
                }
            }
        }

        [HttpPost]
        [PermissionAttribute(PermissionNo = "P0104", IsJson = true)]
        public JsonResult Add(Contact contact)
        {
            JsonResult result = new JsonResult();

            string newContactNo = GetNewIdNumber(IdNumberType.Contact);

            contact.ContactNo = newContactNo;
            contact.CompanyNo = CompanyNo;
            contact.IsActive = true;

            try
            {
                Context.Contact.AddObject(contact);
                Context.SaveChanges();
                result.Data = new { code = 0 };
            }
            catch (Exception ex)
            {
                PutbackNo(newContactNo, IdNumberType.Contact);
                throw ex;
            }

            return result;
        }

        [HttpPost]
        [PermissionAttribute(PermissionNo = "P0105", IsJson = true)]
        public JsonResult Update(Contact contact)
        {
            JsonResult result = new JsonResult();
            string errorMessage = string.Empty;

            Contact OriginalContact = Context.Contact.FirstOrDefault(m => m.ContactNo == contact.ContactNo);
            if (OriginalContact == null)
            {
                errorMessage = "联系人不存在，更新失败。";
            }
            else
            {
                OriginalContact.ContactName = contact.ContactName;
                OriginalContact.Phone = contact.Phone;
                OriginalContact.Mobile = contact.Mobile;
                OriginalContact.Email = contact.Email;
                OriginalContact.SearchKey = contact.SearchKey;
                OriginalContact.CustomerNo = contact.CustomerNo;
                OriginalContact.QQ = contact.QQ;
                OriginalContact.Other = contact.Other;

                try
                {
                    Context.SaveChanges();
                }
                catch
                {
                    errorMessage = "保存联系人信息失败。";
                }
            }

            if (string.IsNullOrEmpty(errorMessage))
            {
                result.Data = new { code = 0 };
            }
            else
            {
                result.Data = new { code = 1, message = errorMessage };
            }

            return result;
        }

        [HttpPost]
        [PermissionAttribute(PermissionNo = "P0106", IsJson = true)]
        public JsonResult Delete(string ContactNo)
        {
            JsonResult result = new JsonResult();
            string errorMessage = string.Empty;

            Contact OriginalContact = Context.Contact.FirstOrDefault(m => m.ContactNo == ContactNo);
            if (OriginalContact == null)
            {
                result.Data = new { code = 1, message = MSG_NoEntityFound };

            }
            else if (IS_DEMO)
            {
                result.Data = new { code = 1, message = MSG_IsDemo };
            }
            else
            {
                OriginalContact.IsActive = false;

                Context.SaveChanges();
                result.Data = new { code = 0 };
            }

            return result;
        }

        public JsonResult GetContact(string ContactNo)
        {
            JsonResult result = new JsonResult();
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;

            Contact contact = Context.Contact.FirstOrDefault(m => m.ContactNo == ContactNo);
            if (contact == null)
            {
                result.Data = new { code = 1, message = "没有找到该联系人信息" };
            }
            else
            {
                Contact OriginalContact = new Contact();

                OriginalContact.ContactName = contact.ContactName;
                OriginalContact.Phone = contact.Phone;
                OriginalContact.Mobile = contact.Mobile;
                OriginalContact.Email = contact.Email;
                OriginalContact.SearchKey = contact.SearchKey;
                OriginalContact.CustomerNo = contact.CustomerNo;
                OriginalContact.ContactNo = contact.ContactNo;
                OriginalContact.QQ = contact.QQ;
                OriginalContact.Other = contact.Other;

                result.Data = OriginalContact;
            }
            return result;
        }

    }
}
